package cn.tedu.qxhouserent.passport.controller;

import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.commons.security.LoginPrincipal;
import cn.tedu.qxhouserent.commons.web.JsonResult;
import cn.tedu.qxhouserent.passport.pojo.param.AdminAddNewParam;
import cn.tedu.qxhouserent.passport.pojo.param.AdminLoginInfoParam;
import cn.tedu.qxhouserent.passport.pojo.param.AdminUpdateInfoParam;
import cn.tedu.qxhouserent.passport.pojo.vo.AdminListItemVO;
import cn.tedu.qxhouserent.passport.pojo.vo.AdminStandardVO;
import cn.tedu.qxhouserent.passport.service.AdminService;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员模块")
@Slf4j
@Validated
public class AdminController {
    @Autowired
    AdminService adminService;


    @PostMapping("/login")
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 50)
    public JsonResult login(AdminLoginInfoParam adminLoginInfoParam,
                            @ApiIgnore HttpServletRequest request) {
        log.debug("开始处理管理员登录业务,参数 {}",adminLoginInfoParam);
        String remoteAddr = request.getRemoteAddr();
        // 处理登录
        String jwt = adminService.login(adminLoginInfoParam);
        return JsonResult.ok(jwt);
    }

    /*// http://localhost:9081/admins/logout
    @PostMapping("/logout")
    @ApiOperation("管理员退出登录")
    @ApiOperationSupport(order = 11)
    public JsonResult<Void> logout(@RequestHeader(HttpConsts.HEADER_AUTHORIZATION) String jwt) {
        log.debug("开始处理【管理员退出登录】的请求，参数：{}", jwt);
        adminService.logout(jwt);
        return JsonResult.ok();
    }*/

    @PostMapping("/add-new")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/add-new')")
    public JsonResult addNew(@Valid AdminAddNewParam adminAddNewParam) {
        log.debug("controller接受【添加管理员】请求：");
        adminService.addNew(adminAddNewParam);
        log.debug("处理完成！");
        return JsonResult.ok();
    }

    @PostMapping("/delete")
    @ApiOperation("根据ID删除管理员")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/delete')")
    public JsonResult deleteById(@Range(min = 1, message = "根据ID删除管理员失败，请提交合法的ID值！")
                             @RequestParam Long id) {
        log.debug("开始处理【根据ID删除管理员】的请求，参数：{}", id);
        adminService.deleteById(id);
        return JsonResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation("修改管理员详情")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult updateById(@RequestParam @Range(min = 1, message = "请提交有效的ID值！") Long id,
                                     @Valid AdminUpdateInfoParam adminUpdateInfoParam) {
        log.debug("开始处理【修改管理员】的业务，参数：{}", adminUpdateInfoParam);
        adminService.updateById(id, adminUpdateInfoParam);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/enable")
    @ApiOperation("启用管理员")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult<Void> setEnable(@PathVariable Long id) {
        log.debug("开始处理【启用管理员】的请求，参数：{}", id);
        adminService.setEnable(id);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/disable")
    @ApiOperation("禁用管理员")
    @ApiOperationSupport(order = 311)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult<Void> setDisable(@PathVariable Long id) {
        log.debug("开始处理【禁用管理员】的请求，参数：{}", id);
        adminService.setDisable(id);
        return JsonResult.ok();
    }

    @GetMapping("/standard")
    @ApiOperation("根据ID查询管理员")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = false, dataType = "long")
    })
    public JsonResult getStandardById(@Range(min = 1, message = "根据ID查询管理员失败，请提交合法的ID值！") Long id, @AuthenticationPrincipal
                                      LoginPrincipal loginPrincipal) {
        log.debug("开始处理【根据ID查询管理员】的请求，参数：{}", id);
        AdminStandardVO result = null;
        if (id == null) {
            result = adminService.getStandardById(loginPrincipal.getId());
        } else {
            result = adminService.getStandardById(id);
        }
        return JsonResult.ok(result);
    }

    @GetMapping("/list")
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "query", value = "查询类型", paramType = "query", dataType = "string")
    })
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    public JsonResult list(@Range(min = 1, message = "查询管理员列表失败，请提供正确的页码值！") Integer page,String query) {
        log.debug("开始处理【查询管理员列表】的请求，页码：{}", page);
        if (page == null || page < 1) {
            page = 1;
        }
        PageData<AdminListItemVO> pageData = null;
        if ("all".equals(query)) {
            pageData = adminService.list(page, Integer.MAX_VALUE);
        } else {
            pageData = adminService.list(page);
        }
        return JsonResult.ok(pageData);
    }


}
